package com.b2c.service;

import com.b2c.common.utils.PageResult;
import com.b2c.mapper.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mr.service.SpuBo;
import com.mr.service.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;


import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName GoodsService
 * @Description: TODO
 * @Author kun
 * @Date 2020/7/27
 * @Version V1.0
 **/
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;



    public PageResult<SpuBo> querySpuByPageAndSort(Integer page, Integer rows, Boolean saleable, String key) {
        // 1、查询SPU
        // 分页,最多允许查100条
        PageHelper.startPage(page, Math.min(rows, 200));

        // 创建查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        // 是否过滤上下架
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }

        // 是否模糊查询
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        Page<Spu> pageInfo = (Page<Spu>) this.spuMapper.selectByExample(example);

        List<SpuBo> list = pageInfo.getResult().stream().map(spu -> {
            // 把spu变为 spuBo
            SpuBo spuBo = new SpuBo();
            // 属性拷贝
            BeanUtils.copyProperties(spu, spuBo);

            // 2、查询spu的商品分类名称,要查三级分类
            List<String> names = this.categoryService.queryNamesByIds(
                    Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            // 将分类名称拼接后存入
            spuBo.setCategoryName(StringUtils.join(names, "/"));

            // 3、查询spu的品牌名称
            BrandEntity brand = this.brandMapper.selectByPrimaryKey(spu.getBrandId());
            spuBo.setBrandName(brand.getName());
            return spuBo;
        }).collect(Collectors.toList());

        return new PageResult<>(pageInfo.getTotal(), list);
    }



    public void delete(Long id) {
        spuMapper.deleteByPrimaryKey(id);
        spuDetailMapper.deleteByPrimaryKey(id);

        Sku skuEx =new Sku();
        skuEx.setSpuId(id);
        List<Sku> skus = skuMapper.select(skuEx);
        skus.forEach(sku -> {
            stockMapper.deleteByPrimaryKey(sku.getId());
            skuMapper.deleteByPrimaryKey(sku.getId());
        });
    }

    //保存spu
    @Transactional
    public void save(SpuBo bo){
        Spu spu=new Spu();
        //保存spu
        BeanUtils.copyProperties(bo,spu);
        Date now=new Date();
        spu.setSaleable(true);
        spu.setValid(true);
        spu.setCreateTime(now);
        spu.setLastUpdateTime(now);
        spuMapper.insert(spu);
        //保存spu详情
        SpuDetail spuDetail=bo.getSpuDetail();
        spuDetail.setSpuId(spu.getId());
        spuDetailMapper.insert(spuDetail);

        //库存
        List<Sku> skuList=bo.getSkus();

        this.saveSkus(skuList,spu.getId());

        sendMessage(spu.getId(),"insert");

    }

    @Transactional
    public void updata(SpuBo bo){

        Spu spu = new Spu();
        BeanUtils.copyProperties(bo,spu);

        spu.setLastUpdateTime(new Date());
        spu.setSaleable(null);
        spu.setValid(null);
        spu.setCreateTime(null);

        spuMapper.updateByPrimaryKeySelective(spu);

        SpuDetail spuDetail = bo.getSpuDetail();
        spuDetailMapper.updateByPrimaryKey(spuDetail);

        Sku sku = new Sku();
        sku.setSpuId(bo.getId());
        List<Sku> skuList=skuMapper.select(sku);

        List<Long> skuIds =skuList.stream().map(s -> s.getId()).collect(Collectors.toList());

        stockMapper.deleteByIdList(skuIds);
        skuMapper.delete(sku);

        this.saveSkus(bo.getSkus(),bo.getId());

        this.sendMessage(spu.getId(),"insert");
    }



    //保存sku
    public void saveSkus(List<Sku> skuList,Long spuId){

        Date now =new Date();
        skuList.forEach(sku ->{
            if(sku.getEnable()){
                //保存sku
                sku.setSpuId(spuId);
                sku.setCreateTime(now);
                sku.setLastUpdateTime(now);
                skuMapper.insert(sku);
                //保存库存
                Stock stock=new Stock();
                stock.setSkuId(sku.getId());
                stock.setStock(sku.getStock());
                stockMapper.insert(stock);
            }
        });
    }

    public SpuDetail queryDetail(Long spuId) {
        return spuDetailMapper.selectByPrimaryKey(spuId);
    }

    public List<Sku> querySkus(Long spuId) {
        Sku skuEx = new Sku();
        skuEx.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(skuEx);
        skus.forEach(sku -> {
            sku.setStock(this.stockMapper.selectByPrimaryKey(sku.getId()).getStock());
        });
        

        return skus;
    }

    public  Spu querySpuById(Long spuId){
        return  spuMapper.selectByPrimaryKey(spuId);
    }


    private void sendMessage(Long id, String type){
        // 发送消息

            this.amqpTemplate.convertAndSend("item." + type, id);

    }

    public Sku querySkuById(Long skuId) {
        return  skuMapper.selectByPrimaryKey(skuId);
    }
}
